package com.legal.aid.web.controller.system;

import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.legal.aid.common.config.WxAppConfig;
import com.legal.aid.common.core.domain.model.WxLoginBody;
import com.legal.aid.common.utils.StringUtils;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.legal.aid.common.constant.Constants;
import com.legal.aid.common.core.domain.AjaxResult;
import com.legal.aid.common.core.domain.entity.SysMenu;
import com.legal.aid.common.core.domain.entity.SysUser;
import com.legal.aid.common.core.domain.model.LoginBody;
import com.legal.aid.common.core.domain.model.LoginUser;
import com.legal.aid.common.utils.SecurityUtils;
import com.legal.aid.framework.web.service.SysLoginService;
import com.legal.aid.framework.web.service.SysPermissionService;
import com.legal.aid.framework.web.service.TokenService;
import com.legal.aid.system.service.ISysMenuService;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    Logger logger = LoggerFactory.getLogger(SysLoginController.class);
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WxAppConfig wxAppConfig;



    /**
     * 微信登录方法
     *
     * @param wxloginBody 登录信息
     * @return 结果
     */
    @PostMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestBody WxLoginBody wxloginBody){
        logger.info("登录参数："+ JSON.toJSONString(wxloginBody));
        //获取登录凭证，只能用一次
        String code = wxloginBody.getCode();
        //密钥
        String encryptedIv = wxloginBody.getEncryptedIv();
        //加密数据
        String encryptedData = wxloginBody.getEncryptedData();
        //向微信服务器发送请求获取用户信息
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppConfig.getAppId()+ "&secret=" + wxAppConfig.getAppSecret() + "&js_code="+ code +"&grant_type=authorization_code";
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject =  JSONObject.parseObject(res);
        //获取session_key,open_id
        System.out.println("Response from WeChat API: " + url);
        System.out.println("Response from WeChat API: " + res);
        String sessionKey = jsonObject.getString("session_key");
        if(sessionKey == null){
            return AjaxResult.error("获取openid失败,微信登录失败");
        }
        String openid = jsonObject.getString("openid");


        //解密
        String decryptResult = " ";
        try {
            decryptResult = decrypt(sessionKey,encryptedIv,encryptedData);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("微信登录失败");
        }
        if(StringUtils.hasText(decryptResult)) {
            //如果解析成功，获取Token
            String token = loginService.wxLogin(decryptResult);
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put(Constants.TOKEN, token);
            return ajaxResult;
        }else {
            return AjaxResult.error("微信登录失败");
        }
    }

    public String decrypt(String sessionKey, String encryptedIV, String encryptedData)throws Exception {
        logger.info("sessionKey: " + sessionKey);
        logger.info("encryptedIV: " + encryptedIV);
        logger.info("encryptedData: " + encryptedData);
        if (StringUtils.isEmpty(sessionKey) || StringUtils.isEmpty(encryptedIV) || StringUtils.isEmpty(encryptedData)) {
            throw new IllegalArgumentException("解密参数不能为空");
        }

        byte[] key = Base64.decode(sessionKey);
        byte[] iv = Base64.decode(encryptedIV);
        byte[] encData = Base64.decode(encryptedData);
        int base = 16;
        if (key.length % base != 0) {
            int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }
        if (iv.length % base != 0) {
            int groups = iv.length / base + (iv.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(iv, 0, temp, 0, iv.length);
            iv = temp;
        }
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        String resultStr = null;
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, spec, ivSpec);
            resultStr = new String(cipher.doFinal(encData), "utf-8");
        } catch (Exception e) {
            logger.info("解析错误");
            e.printStackTrace();
        }
        return resultStr;
    }

        /**
         * 登录方法
         *
         * @param loginBody 登录信息
         * @return 结果
         */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (loginUser.getPermissions() != null && !loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
